<?php

namespace backend\models;

use Yii;
use yii\behaviors\TimestampBehavior;


/**
 * This is the model class for table "{{%plan_data}}".
 *
 * @property integer $id
 * @property integer $complete
 * @property integer $contract
 * @property integer $created_at
 * @property integer $updated_at
 */
class PlanData extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%plan_data}}';
    }


    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['type', 'contract_name', 'contract'], 'required'],
            [['complete', 'contract_img'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'type' => '合同类型',
            'contract_name' => '合同名称',
            'contract_img' => '合同图片',
            'complete' => '已完成金额',
            'contract' => '当前合同金额',
            'created_at' => '添加时间',
            'updated_at' => '修改时间',
        ];
    }

    public function create($imageUrl)
    {
        $model = new PlanData();
        $type = $this->type;
        $complete = $this->complete ? $this->complete : 0;
        $contract = $this->contract;
        $contract_name = $this->contract_name;

        $model->type = $type;
        $model->complete = $complete + $contract;
        $model->contract = $contract;
        $model->contract_name = $contract_name;
        $model->contract_img = $imageUrl;

        if (!$model->save()) {
            return false;
        }
        return true;
    }


    public function edit($imageUrl)
    {
        $model = PlanData::findOne(['id' => $this->id]);

        $type = $this->type;
        $complete = $this->complete ? $this->complete : 0;
        $contract = $this->contract;
        $contract_name = $this->contract_name;
        $contract_num = $model->contract - $contract;
        $model->type = $type;
        $model->complete = $complete - $contract_num;
        $model->contract = $contract;
        $model->contract_name = $contract_name;
        $model->contract_img = $imageUrl ? $imageUrl : $model->contract_img;

        if (!$model->save()) {
            return false;
        }
        return true;
    }
}
